from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, JSON, Text, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from database.db import Base


class ExceptionLog(Base):
    __tablename__ = "exception_logs"

    id = Column(Integer, primary_key=True, index=True, comment="异常日志ID")
    exception_type = Column(String(50), nullable=False, comment="异常类型：system_error/device_failure/task_interruption")
    exception_level = Column(String(20), nullable=False, comment="异常级别：critical/warning/info")
    title = Column(String(200), nullable=False, comment="异常标题")
    description = Column(Text, nullable=True, comment="异常详细描述")
    
    # 关联信息
    drone_id = Column(Integer, ForeignKey("drones.id"), nullable=True, comment="关联无人机ID")
    task_id = Column(Integer, ForeignKey("tasks.id"), nullable=True, comment="关联任务ID")
    detection_log_id = Column(Integer, ForeignKey("detection_logs.id"), nullable=True, comment="关联检测日志ID")
    
    # 位置信息
    location = Column(JSON, nullable=True, comment="异常发生位置信息")
    
    # 处理信息
    responsible_user_id = Column(Integer, ForeignKey("users.id"), nullable=True, comment="责任人ID")
    status = Column(String(20), nullable=False, default="pending", comment="处理状态：pending/resolved")
    resolution_description = Column(Text, nullable=True, comment="解决描述")
    resolution_time = Column(DateTime, nullable=True, comment="解决时间")
    
    # 时间信息
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, comment="异常发生时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False, comment="更新时间")
    
    # 关系
    drone = relationship("Drone", backref="exception_logs")
    task = relationship("Task", backref="exception_logs")
    detection_log = relationship("DetectionLog", backref="exception_logs")
    responsible_user = relationship("User", backref="responsible_exception_logs")